/**
 * Licensed to Jasig under one or more contributor license agreements. See the NOTICE file distributed with this work
 * for additional information regarding copyright ownership. Jasig licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy
 * of the License at:
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
 * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 */

package com.baijia.commons.session;

import com.baijia.commons.authentication.Assertion;
import com.baijia.commons.config.PassportClientConfig;
import com.baijia.commons.constant.Constant;
import com.baijia.commons.util.PPCommonUtils;

import com.mashape.unirest.http.JsonNode;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import java.io.IOException;

import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @title AbstractPassportFilter
 * @desc 初始化passport client filter部分公共属性
 * @author caoliang
 * @date 2015年12月1日
 * @version 1.0
 */
public abstract class AbstractPassportFilter extends AbstractConfigurationFilter {

    /** session attribute中assertion的key */
    public static final String CONST_PASSPORT_ASSERTION = "_const_passport_assertion_";

    public static final String CONST_PASSPORT_ID = "_const_passport_id_";

    protected final Logger logger = LoggerFactory.getLogger(getClass());

    /** ST的key */
    private String artifactParameterName = Constant.ARTIFACTPARAMETERNAME;

    /** service的key */
    // private String serviceParameterName = Constant.SERVICEPARAMETERNAME;
    private String serviceParameterName = Constant.TARGET_SERVICE_PARAMETER_NAME;

    /** 默认开启url encode，避免特殊字符 */
    private boolean encodeServiceUrl = true;

    /**
     * 客户端地址 {protocol}:{hostName}:{port}
     */
    private String serverName;

    /**
     * 客户端的url，serverName也可以写url，二选一
     */
    private String service;

    protected PassportClientConfig passportConfig;

    @Override
    public final void init(final FilterConfig filterConfig) throws ServletException {
        if (!isIgnoreInitConfiguration()) {
            setArtifactParameterName(getPropertyFromInitParams(filterConfig, "artifactParameterName",
                Constant.ARTIFACTPARAMETERNAME));
            logger.trace("Loading artifact parameter name property: " + this.artifactParameterName);
            setServiceParameterName(getPropertyFromInitParams(filterConfig, "serviceParameterName",
                Constant.SERVICEPARAMETERNAME));
            logger.trace("Loading serviceParameterName property: " + this.serviceParameterName);

            ServletContext context = filterConfig.getServletContext();
            WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(context);
            passportConfig = applicationContext.getBean(PassportClientConfig.class);
            setServerName(passportConfig.getClientName());
            logger.info("PassportConfig {}", passportConfig);
            initInternal(filterConfig);
        }
        init();
    }

    /**
     * 在init之前初始化一些属性
     * 
     * @param filterConfig
     * @throws ServletException
     */
    protected void initInternal(final FilterConfig filterConfig) throws ServletException {
        appId = passportConfig.getAppId();
    }

    public void init() {
        PPCommonUtils.assertNotNull(this.artifactParameterName, "artifactParameterName cannot be null.");
        PPCommonUtils.assertNotNull(this.serviceParameterName, "serviceParameterName cannot be null.");
        PPCommonUtils.assertTrue(PPCommonUtils.isNotEmpty(this.serverName) || PPCommonUtils.isNotEmpty(this.service),
            "serverName or service must be set.");
        PPCommonUtils.assertTrue(PPCommonUtils.isBlank(this.serverName) || PPCommonUtils.isBlank(this.service),
            "serverName and service cannot both be set.  You MUST ONLY set one.");
    }

    @Override
    public void destroy() {
        // nothing to do
    }

    protected final String constructServiceUrl(final HttpServletRequest request, final HttpServletResponse response) {
        return PPCommonUtils.constructServiceUrl(request, response, this.service, this.serverName,
            this.artifactParameterName, this.encodeServiceUrl);
    }

    /**
     * serverName不能为空，结尾不能是 '/'
     * 
     * @param serverName
     */
    public final void setServerName(final String serverName) {
        if (serverName != null && serverName.endsWith("/")) {
            this.serverName = serverName.substring(0, serverName.length() - 1);
            if (logger.isDebugEnabled()) {
                logger.debug(String.format("Eliminated extra slash from serverName [%s].  It is now [%s]", serverName,
                    this.serverName));
            }
        } else {
            this.serverName = serverName;
        }
    }

    protected boolean isUserLogin(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession(false);
        Assertion assertion = session != null ? (Assertion) session.getAttribute(CONST_PASSPORT_ASSERTION) : null;
        return assertion != null && StringUtils.isNotBlank(assertion.getUsername());
    }

    protected void needLoginResponse(HttpServletRequest request, HttpServletResponse response) throws IOException {
        JsonNode resp =
            new JsonNode(String.format("{\"code\":%d,\"status\":%d,  \"redirectUrl\":\"%s\"}", 1, 700,
                passportConfig.getClientLoginAddr()));
        response.setContentType("application/json; charset=utf-8");
        response.setCharacterEncoding("utf-8");
        response.getWriter().write(resp.toString());
    }

    public final void setService(final String service) {
        this.service = service;
    }

    public final void setArtifactParameterName(final String artifactParameterName) {
        this.artifactParameterName = artifactParameterName;
    }

    public final void setServiceParameterName(final String serviceParameterName) {
        this.serviceParameterName = serviceParameterName;
    }

    public final void setEncodeServiceUrl(final boolean encodeServiceUrl) {
        this.encodeServiceUrl = encodeServiceUrl;
    }

    public final String getArtifactParameterName() {
        return this.artifactParameterName;
    }

    public final String getServiceParameterName() {
        return this.serviceParameterName;
    }
}
